package com.common.receiver;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import com.common.event.NetWorkChangeEvent;

import de.greenrobot.event.EventBus;

/**
 * Created by mark on 15/3/27.
 */
public class NetWorkChangeReceiver extends BaseReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(TextUtils.equals(action, ConnectivityManager.CONNECTIVITY_ACTION)){
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null) {
                NetworkInfo [] netWorkInfoArray = connectivityManager.getAllNetworkInfo();
                for (int i = 0; i < netWorkInfoArray.length; i++) {
                    NetworkInfo networkInfo = netWorkInfoArray[i];
                    NetworkInfo.State state = networkInfo.getState();
                    if (NetworkInfo.State.CONNECTED == state) {
                        EventBus.getDefault().post(new NetWorkChangeEvent(true,networkInfo.getType()));
                        return;
                    }
                }
            }

            //没有执行return,则说明当前无网络连接
            EventBus.getDefault().post(new NetWorkChangeEvent(false,-1));
        }
    }
}
